# -*- encoding: utf-8 -*-
__author__ = 'jia200x'

from django.template.loader import get_template
from django.template import Context, RequestContext
from django.http import HttpResponse, StreamingHttpResponse
from api.models import Tema, VN
from django.shortcuts import render
from django.core.context_processors import csrf
import datetime
import time
from django.db.models import Count

def index(request):
    t = get_template('untitled.html')
    html = t.render(Context())
    return HttpResponse(html)

def gracias(request):
    t = get_template('gracias.html')
    html = t.render(Context())
    return HttpResponse(html)

def resultados_f(request):
    tm = {}

    temas = Tema.objects.all().annotate(n_votos=Count('vn')).order_by('area','-n_votos')
    ar = []
    for t in temas:
        first = False
        if tm.get(t.area,None) == None:
            first = True
            tm[t.area] = []
        tm[t.area].append([t.titulo,t.n_votos, first])

    cuentas = VN.objects.all().values('uai','na').distinct().annotate(count=Count('uai')).order_by('-count')
    uais = VN.objects.all().values_list('uai').distinct()
    data = []
    for u in uais:
        d = {}
        cuentas = VN.objects.filter(uai=u[0]).values('na').annotate(count=Count('na',distinct=True))
        d['uai'] = u[0]
        d['count'] = cuentas.count
        data.append(d)

    c = Context({'temas': tm, 'data': data})
    return render(request,'resultados.html',c)
def resultados(request):
    tm = {}

    temas = Tema.objects.all().annotate(n_votos=Count('vn')).order_by('area','-n_votos')
    for t in temas:
        if tm.get(t.area,None) == None:
            tm[t.area] = []
        tm[t.area].append([t.titulo,t.n_votos])

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="resultados.csv"'

    # The data is hard-coded here, but you could load it from a database or
    # some other source.
    csv_data = Tema.objects.all()

    t = get_template('resultados.csv')
    c = Context({
        'temas': tm,
    })
    response.write(t.render(c))
    return response#, ",", t.area,",",t.descripcion,",",t.autor,",",t.uai,",",t.academico,"\n"

def vota(request):
    t = get_template('vota.html')
    t_educacion = Tema.objects.filter(area='EDUCACIÓN E INFANCIA')
    t_eyd = Tema.objects.filter(area='ECONOMÍA Y DESARROLLO')
    t_energia = Tema.objects.filter(area='ENERGÍA Y MEDIO AMBIENTE')
    t_pd = Tema.objects.filter(area='POBREZA Y DESIGUALDAD')
    t_salud = Tema.objects.filter(area='SALUD')
    t_vivienda = Tema.objects.filter(area='VIVIENDA Y CIUDAD')

    html = t.render(Context({'temas_educacion':t_educacion,'temas_energia':t_energia,'temas_eyd':t_eyd,'temas_pd':t_pd,
                             'temas_salud':t_salud,'temas_vivienda':t_vivienda}))
    return HttpResponse(html)


def tema(request, identifier):
    te = get_template('tema.html')
    try:
        t = Tema.objects.get(id=identifier)
    except:
        return HttpResponse("Error: No encontrado")
    html = te.render(Context({'titulo': t.titulo,'descripcion':t.descripcion,'autor':t.autor,'uai':t.uai}))
    return HttpResponse(html)

def stats(request):
    template = get_template('stats.html')
    tm = {}

    temas = Tema.objects.all().annotate(n_votos=Count('vn')).order_by('area','-n_votos')
    ar = []
    for t in temas:
        first = False
        if tm.get(t.area,None) == None:
            first = True
            tm[t.area] = []
        tm[t.area].append([t.titulo,t.n_votos, first])
    n_votos = VN.objects.all().values('na').distinct().count()
    c = Context({'temas': tm,'n_votos': n_votos })
    return render(request,'stats.html',c)

def post_voto(request):
    if request.method == "POST":
        #Obtener los datos
        t_educacion = request.POST.get('opciones_educacion','')
        t_energia = request.POST.get('opciones_energia','')
        t_eyd = request.POST.get('opciones_eyd','')
        t_pd = request.POST.get('opciones_pd','')
        t_salud = request.POST.get('opciones_salud','')
        t_vivienda = request.POST.get('opciones_vivienda','')
        na = request.POST.get('na','')
        uai = request.POST.get('uai','')
        success = []
        error = []

        na_valid = True
        if (na == ''):
            na_valid = False

        if (na_valid):
            if (t_educacion != ""):
                try:
                    t=VN(na=na,tema=Tema.objects.get(id=int(t_educacion)),uai=uai).save()
                    success.append('Educación e infancia')
                except:
                    error.append('Educación e infancia')

            if (t_energia != ""):

                try:
                    t=VN(na=na,tema=Tema.objects.get(id=int(t_energia)),uai=uai).save()
                    success.append('Energía y medio ambiente')
                except:
                    error.append('Energía y medio ambiente')

            if (t_eyd != ""):
                try:
                    t=VN(na=na,tema=Tema.objects.get(id=int(t_eyd)),uai=uai).save()
                    success.append('Economía y desarrollo')
                except:
                    error.append('Economía y desarrollo')

            if (t_pd != ""):
                try:
                    t=VN(na=na,tema=Tema.objects.get(id=int(t_pd)),uai=uai).save()
                    success.append('Pobreza y desigualdad')
                except:
                    error.append('Pobreza y desigualdad')

            if (t_salud != ""):
                try:
                    t=VN(na=na,tema=Tema.objects.get(id=int(t_salud)),uai=uai).save()
                    success.append('Salud')
                except:
                    error.append('Salud')

            if (t_vivienda != ""):
                try:
                    t=VN(na=na,tema=Tema.objects.get(id=int(t_vivienda)),uai=uai).save()
                    success.append('Vivienda y ciudad')
                except:
                    error.append('Vivienda y ciudad')

        #t = get_template('post.html')
        c=Context({'error': error, 'success': success, 'n_error': len(error)>0, 'n_success':len(success)>0, 'na_valid':na_valid})
        c.update(csrf(request))
        #html = t.render(c)
        return render(request,'post.html',c)
    else:
        return HttpResponse("")

def stream_response(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="temas.csv"'

    # The data is hard-coded here, but you could load it from a database or
    # some other source.
    csv_data = Tema.objects.all()

    t = get_template('temas.csv')
    c = Context({
        'data': csv_data,
    })
    response.write(t.render(c))
    return response#, ",", t.area,",",t.descripcion,",",t.autor,",",t.uai,",",t.academico,"\n"

def stream_votos(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="votos.csv"'

    # The data is hard-coded here, but you could load it from a database or
    # some other source.

    cuentas = VN.objects.all().values('uai','na').distinct().annotate(count=Count('uai')).order_by('-count')
    uais = VN.objects.all().values_list('uai').distinct()
    data = []
    for u in uais:
        d = {}
        cuentas = VN.objects.filter(uai=u[0]).values('na').annotate(count=Count('na',distinct=True))
        d['uai'] = u[0]
        d['count'] = cuentas.count
        data.append(d)

    t = get_template('votos.csv')
    sorted(data,key= lambda o:o['count'],reverse=True)
    c = Context({
        'data': data,
    })
    response.write(t.render(c))
    return response#, ",", t.area,",",t.descripcion,",",t.autor,",",t.uai,",",t.academico,"\n"